<template>
  <div class="init-container">
    <div class="mask-container" v-if="isMask"></div>
    <div class="analyzer-container y-scroll">
      <div class="header">
        <div class="header-left">
          <span>分析仪连接状态: </span>
          <span class="active">{{
            analyerConnectState ? '正常' : '失败'
          }}</span>
        </div>
        <div class="header-right">
          <span>当前硫酸亚铁铵浓度：</span>
          <vxe-input v-model="sulfuricNum.value" readonly></vxe-input>
        </div>
      </div>

      <vxe-table
        border
        show-overflow
        :data="tableData"
        :edit-config="{ trigger: 'manual', mode: 'cell' }"
        :column-config="{ resizable: true }"
        auto-resize
        header-align="center"
      >
        <vxe-column
          field="paramName"
          title="参数名称"
          fixed="left"
        ></vxe-column>
        <vxe-column v-for="slot in slots" :key="slot" :title="slotTitles[slot]">
          <template #default="{ row }">
            <div class="cell-content">
              <template v-if="row.editable && row[slot].editable">
                <vxe-input
                  v-model="row[slot].value"
                  type="number"
                  :disabled="!row[slot].editable"
                  @blur="handleBlur(row, slot)"
                ></vxe-input>
              </template>
              <!-- <template v-if="row.type === 'switch'">
                <span
                  class="status-switch"
                  :class="{ active: row[slot].value }"
                  @click="toggleSwitch(row, slot)"
                >
                  {{ row[slot].value ? '自动' : '手动' }}
                </span>
              </template> -->

              <template
                v-if="row.paramName === '添加方式' && row[slot].editable"
              >
                <span
                  class="status-switch"
                  :class="{ active: row[slot].value }"
                  @click="toggleSwitch(row, slot)"
                >
                  {{ row[slot].value ? '按分析仪添加' : '按计挂数添加' }}
                </span>
              </template>

              <template
                v-if="row.paramName === '状态按钮' && row[slot].editable"
              >
                <span
                  class="status-switch"
                  :class="{ active: row[slot].value }"
                  @click="toggleSwitch(row, slot)"
                >
                  {{ row[slot].value ? '自动' : '手动' }}
                </span>
              </template>

              <template v-if="row.type === 'indicator'">
                <div
                  class="breathing-light"
                  :class="{ active: row[slot].value }"
                ></div>
              </template>

              <span v-if="row.type === 'text'">
                {{ formatValue(row[slot].value) }}
              </span>
            </div>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
  </div>
</template>

<script lang="ts">
import { VxeTable, VxeColumn, VxeInput } from 'vxe-table';
import { Tsrv, T_srv, ifs, ts, vue, I_cmd, T_cmd, tableConfig } from './config';

interface SlotConfig {
  value: number | boolean | string;
  editable: boolean;
  originalValue?: any;
  validator?: (val: any) => boolean;
}

@T_srv.comp({
  components: { VxeTable, VxeColumn, VxeInput }
})
export default class CAnalyzer extends vue {
  private slots = [
    'chrome15',
    'sulfuric11',
    'sulfuric12',
    'alkali2',
    'bright6',
    'chromeSeal20'
  ];

  /* 遮罩 */
  public isMask: boolean = false;

  private slotTitles = {
    chrome15: '铬酸15槽',
    sulfuric11: '硫酸11槽',
    sulfuric12: '硫酸12槽',
    alkali2: '碱蚀2槽',
    bright6: '出光6槽',
    chromeSeal20: '铬酸封闭20槽'
  };

  private ecDetCodes: string[] = [];

  private GT_command = new T_cmd();

  private tableData = tableConfig();
  // private tableData: any;

  public sulfuricNum = {
    code: 'myCAnalyzer106',
    value: 0
  };

  private analyerConnectState = true;

  created() {
    this.init();
  }

  mounted() {
    this.GT_command.init(this);
    this.$bus.$on(
      '__PLC_CONNSTATE__',
      (data: { connState: boolean; ecBoxName: string }) => {
        if (data.ecBoxName === 'mianyang-1') {
          this.analyerConnectState = data.connState;
          if (data.connState) {
            if (!this.GT_command.isOpenTask) {
              this.GT_command.startTask();
            }
          } else {
            this.GT_command.stopTask();
          }
        }
      }
    );
    this.GT_command.startTask();
  }

  destroyed() {
    this.GT_command.stopTask();
    this.$bus.$off('__PLC_CONNSTATE__');
  }

  private init() {
    this.ecDetCodes = [];
    this.ecDetCodes.push(this.sulfuricNum.code);
    for (const el of this.tableData) {
      Object.keys(el).forEach(key => {
        if (!Tsrv.noValue(el[key].code)) {
          this.ecDetCodes.push(el[key].code);
        }
      });
    }

    const chunkSize = 20;
    const chunks = [];
    for (let i = 0; i < this.ecDetCodes.length; i += chunkSize) {
      chunks.push(this.ecDetCodes.slice(i, i + chunkSize));
    }

    const promises = chunks.map(chunk => Tsrv.readPlcData(chunk));
    Promise.all(promises).then(results => {
      const combinedResult = Object.assign({}, ...results);
      if (typeof combinedResult !== 'boolean') {
        for (const el of this.tableData) {
          Object.keys(el).forEach(key => {
            if (!Tsrv.noValue(el[key].code)) {
              el[key].value = combinedResult[el[key].code].v;
            }
          });
        }
        this.sulfuricNum.value = combinedResult[this.sulfuricNum.code].v;
      }
    });
  }

  private init1() {
    this.tableData = [
      // 可编辑数值参数
      this.createRow('加药开启下限阈值（g/L）', 'number', true),
      this.createRow('加药开启上限阈值（g/L）', 'number', true),
      this.createRow('槽体积L', 'number', true),
      this.createRow('加药判定值（g/L）', 'number', true),
      this.createRow('化学品浓度（g/L）', 'number', true),
      this.createRow('加药泵功率（L/H）', 'number', true),
      this.createRow('加药时间系数', 'number', true),
      this.createRow('计算公式目标值(g/L)', 'number', true),
      this.createRow('单次加药量(L)', 'number', true),
      this.createRow('加药泵功率系数', 'number', true),
      this.createRow('加药1过程值(g/L)', 'number', true),
      this.createRow('硫酸亚铁铵浓度', 'number', {
        sulfuric11: true,
        sulfuric12: true
      }),
      this.createRow('排废运行时间', 'number', {
        sulfuric11: true,
        sulfuric12: true,
        chrome15: true
      }),
      // 仅显示参数
      this.createRow('加药量累计值', 'text', false),
      this.createRow('加药量累计时间值(S)', 'text', false),
      // 呼吸灯参数
      this.createRow('取样开始标记', 'indicator', false),
      this.createRow('PLC取样开始标记', 'indicator', false),
      // 特殊参数
      this.createRow('铬酸/硫酸(g/L)结果1', 'number', true),
      this.createRow('铬酸/硫酸(g/L)结果2', 'number', {
        sulfuric11: true,
        sulfuric12: true,
        alkali2: true
      }),
      this.createRow('取样前搅拌时间(S)', 'number', { chrome15: true }),
      this.createRow('搅拌后静置时间(S)', 'number', { chrome15: true }),
      this.createRow('取样中进行时间(S)', 'number', { chrome15: true }),
      // 切换按钮
      this.createRow('添加方式', 'switch', {
        alkali2: true,
        bright6: true,
        chromeSeal20: true
      }),
      this.createRow('状态按钮', 'switch', {
        alkali2: true,
        bright6: true,
        chromeSeal20: true
      })
    ];
  }

  private createRow(paramName: string, type: string, editableSlots: any) {
    const row: any = {
      paramName,
      type,
      editable: type === 'number',
      originalValues: {}
    };

    this.slots.forEach((slot, index) => {
      const isEditable =
        typeof editableSlots === 'boolean'
          ? editableSlots
          : !!editableSlots[slot];

      row[slot] = {
        value: type === 'number' ? 0.0 : type === 'text' ? '0.00' : true,
        editable: isEditable,
        originalValue:
          type === 'number' ? 0.0 : type === 'text' ? '0.00' : true,
        code: `my${index}`
      };

      if (type === 'number') {
        row[slot].validator = (val: any) =>
          /^[0-9]{1}\.[0-9]{2}$/.test(val.toString());
      }
    });

    return row;
  }

  private formatValue(value: any) {
    return typeof value === 'number' ? value.toFixed(2) : value.toString();
  }

  private handleBlur(row: any, slot: string) {
    if (row[slot].validator && !row[slot].validator(row[slot].value)) {
      this.$Message.error('数值格式错误（整数1位，小数2位）');
      row[slot].value = row[slot].originalValue;
      return;
    }

    if (row[slot].value !== row[slot].originalValue) {
      this.updateData(row, slot);
      row[slot].originalValue = row[slot].value;
    }
  }

  private toggleSwitch(row: any, slot: string) {
    if (row[slot].editable) {
      row[slot].value = !row[slot].value;
      this.updateData(row, slot);
    }
  }

  private async updateData(row: any, slot: string) {
    try {
      const payload = {
        param: row.paramName,
        slot: this.slotTitles[slot],
        code: row[slot].code,
        value: row[slot].value
      };
      // 调用实际接口
      const data = [
        { ecDetCode: payload.code, value: payload.value.toString() }
      ];
      Tsrv.writePlcData(data).then(_ => {
        Tsrv.readPlcData([payload.code]).then(res => {
          if (typeof res !== 'boolean') {
            row[slot].value = res[payload.code].v;
          }
        });
      });
    } catch (error) {
      console.error('更新失败:', error);
      row[slot].value = row[slot].originalValue;
    }
  }
}
</script>

<style lang="scss" scoped>
.analyzer-container {
  width: 100%;
  height: 100%;
  padding: 20px;
  background: #f0eded;

  ::v-deep .vxe-table--render-wrapper {
    overflow-x: auto;
  }
}

.header {
  padding-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-content: center;
}

.cell-content {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 40px;
}

.status-switch {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  background: #f5f5f5;
  color: #666;
  transition: all 0.3s;

  &.active {
    background: #1890ff;
    color: white;
  }
}

@keyframes breathing {
  0% {
    opacity: 0.4;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.4;
  }
}

.breathing-light {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #ccc;

  &.active {
    background: #1890ff;
    animation: breathing 1.5s ease-in-out infinite;
  }
}
</style>
